package com.emotion.sshticket.controllers;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.emotion.sshticket.mail.MailUtil;
import com.emotion.sshticket.mail.MailUtil;
import com.emotion.sshticket.services.AdminService;
import com.emotion.sshticket.utilitys.PagingUtil;
import com.emotion.sshticket.utilitys.ValueUtil;
import com.emotion.sshticket.vo.AdminUserVO;
import com.emotion.sshticket.vo.TicketVO;

@Controller
public class AdminController {

	@Resource(name="messageSource")
	private MessageSource messageSource;

	@Resource(name="propertySource")
	private Properties propertySource;

	@Resource(name="adminService")
	private AdminService adminService;

 	@RequestMapping("/admin/loginForm.do")
	public ModelAndView loginForm(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		try {
			// 관리자 페이지 로그인 창 호출
			mv.setViewName("admin/loginForm");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	@RequestMapping("/admin/login.do")
	@ResponseBody
	public JSONObject login(HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			String userId =	ValueUtil.nullToString(request.getParameter("userId"));
			String userPw =	ValueUtil.nullToString(request.getParameter("userPw"));
			// 로그인 처리
			AdminUserVO adminUserVO = adminService.getAdminLoginInfo(userId, userPw);
			if (adminUserVO == null) {
				String message = messageSource.getMessage("error.admin.wrong.idpw", null, request.getLocale());
				throw new Exception(message);
			}

			HttpSession session = request.getSession(true);
			session.setAttribute("adminUser", adminUserVO);
			jsonObject.put("result", "OK");
			jsonObject.put("foward", "/admin/ticketList.do");
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("errorMsg", e.getMessage());
		}
		return jsonObject;
	}

	@RequestMapping("/admin/logout.do")
	@ResponseBody
	public JSONObject logout(HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			HttpSession session = request.getSession(false);
			session.invalidate();
			jsonObject.put("result", "OK");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	@RequestMapping("/admin/ticketList.do")
	public ModelAndView ticketList(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		try {
			// 검색조건 기타등등
			String isExcel = 	ValueUtil.nullToString(request.getParameter("isExcel"));
			String isSearch = 	ValueUtil.nullToString(request.getParameter("isSearch"));
			String userNm = 	ValueUtil.nullToString(request.getParameter("userNm"));
			String userHnm = 	ValueUtil.nullToString(request.getParameter("userHnm"));
			String userEmail = 	ValueUtil.nullToString(request.getParameter("userEmail"));
			String payState = 	ValueUtil.nullToString(request.getParameter("payState"));
			String mailState =	ValueUtil.nullToString(request.getParameter("mailState"));
			String phone = 		ValueUtil.nullToString(request.getParameter("phone"));
			String addr1 = 		ValueUtil.nullToString(request.getParameter("addr1"));
			String addr2 = 		ValueUtil.nullToString(request.getParameter("addr2"));
			String addr3 = 		ValueUtil.nullToString(request.getParameter("addr3"));
			int num = 			ValueUtil.nullToInt(request.getParameter("page"),1);
			int listLimit = 15;
			int page = (num - 1) * listLimit;
			int totalCount = 0;

			Map<String, Object> m = new HashMap<String, Object>();
			m.put("userNm", userNm);
			m.put("userHnm", userHnm);
			m.put("userEmail", userEmail);
			m.put("payState", payState);
			m.put("phone", phone);
			m.put("addr1", addr1);
			m.put("addr2", addr2);
			m.put("addr3", addr3);
			m.put("mailState", mailState);
			m.put("isSearch", isSearch);
			String result = "/admin/ticketList";
			if(!"Y".equals(isExcel)){
				m.put("num", num);
				m.put("page", page);
				m.put("listLimit", listLimit);
				totalCount = adminService.getTotalTicketList(m);
			} else {
				result = "/admin/ticketListExcel";
			}

			m.put("totalCount", totalCount);
			List<TicketVO> ticketList = adminService.getTicketList(m);

			int pageRange = 10;
			String url = ValueUtil.getRequestURLWithParameters(request);
			mv.addObject("paging", PagingUtil.getPaging(num, pageRange, totalCount, listLimit));
			mv.addObject("addrList", ValueUtil.getAddrList());
			mv.addObject("ticketList", ticketList);
			mv.addObject("SearchMap", m);
			mv.setViewName(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	@RequestMapping("/admin/ticketDetail.do")
	public ModelAndView ticketDetail(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		try {
			String seq = 	ValueUtil.nullToString(request.getParameter("seq"));

			TicketVO ticketBean = new TicketVO();
			ticketBean = adminService.getTicketInfo(seq);

			String phone = ticketBean.getPhone();
			String postAddr = ticketBean.getPostAdd();

			String phone1 = phone.split("-")[0];
			String phone2 = phone.split("-")[1];
			String phone3 = phone.split("-")[2];

			String post1 = postAddr.split("-")[0];
			String post2 = postAddr.split("-")[1];

			mv.addObject("ticket", ticketBean);
			mv.addObject("phone1", phone1);
			mv.addObject("phone2", phone2);
			mv.addObject("phone3", phone3);
			mv.addObject("post1", post1);
			mv.addObject("post2", post2);
			mv.addObject("addrList", ValueUtil.getAddrList());
			mv.setViewName("/admin/ticketView");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	@RequestMapping("/admin/updateTicketDetail.do")
	@ResponseBody
	public ModelAndView updateTicketDetail(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView();
		try {

			String userNameF =	ValueUtil.nullToString(request.getParameter("userNameF"));
			String userNameS =	ValueUtil.nullToString(request.getParameter("userNameS"));
			String hiraganaF =	ValueUtil.nullToString(request.getParameter("hiraganaF"));
			String hiraganaS =	ValueUtil.nullToString(request.getParameter("hiraganaS"));
			String userEmail =	ValueUtil.nullToString(request.getParameter("userEmail"));
			String payState = 	ValueUtil.nullToString(request.getParameter("payState"));
			String addr1 =		ValueUtil.nullToString(request.getParameter("addr1"));
			String addr2 =		ValueUtil.nullToString(request.getParameter("addr2"));
			String addr3 =		ValueUtil.nullToString(request.getParameter("addr3"));
			String phone =		ValueUtil.nullToString(request.getParameter("phone"));
			String mail_yn =		ValueUtil.nullToString(request.getParameter("mailState"));
			int seq =			Integer.parseInt(ValueUtil.nullToString(request.getParameter("seq")));

			TicketVO ticketVO = new TicketVO();
			ticketVO.setUserNameF(userNameF);
			ticketVO.setUserNameS(userNameS);
			ticketVO.setHiraganaF(hiraganaF);
			ticketVO.setHiraganaS(hiraganaS);
			ticketVO.setUserEmail(userEmail);
			ticketVO.setAddr1(addr1);
			ticketVO.setAddr2(addr2);
			ticketVO.setAddr3(addr3);
			ticketVO.setPhone(phone);
			ticketVO.setPayState(payState);
			ticketVO.setMailYn(mail_yn);
			ticketVO.setSeq(seq);

			adminService.updateTicketInfo(ticketVO);

			mv.setViewName("redirect:/admin/ticketList.do");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return mv;
	}

	
	@RequestMapping("/admin/updatePayState.do")
	@ResponseBody
	public JSONObject updatePayState(HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			
			String board_no = request.getParameter("user_seq");
			String[] _SEQ = board_no.split(",");
			
			System.out.println(_SEQ);
			if(_SEQ.length>0) {
				for(int i=0;i<_SEQ.length;i++) {
					if(!"".equals(_SEQ[i])) {
						String flagSeq = _SEQ[i];
						adminService.updatePayState(flagSeq);
					}
				}
			}
			
			jsonObject.put("result", "OK");
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("errorMsg", e.getMessage());
		}
		return jsonObject;
	}
	
	@RequestMapping("/admin/sendMail.do")
	@ResponseBody
	public JSONObject sendMail(HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			
			String seq = 	ValueUtil.nullToString(request.getParameter("user_seq"));

			TicketVO ticketBean = new TicketVO();
			ticketBean = adminService.getTicketInfo(seq);
			
			String user_email = ticketBean.getUserEmail();
			String user_name = ticketBean.getUserNameF()+" "+ticketBean.getUserNameS();
			String phone = ticketBean.getPhone();
			String oneticket = Integer.toString(ticketBean.getOnceTicket());
			String twiticket = Integer.toString(ticketBean.getTwiceTicket());
			String hiragana = ticketBean.getHiraganaF()+" "+ticketBean.getHiraganaS();
			String post = ticketBean.getPostAdd();
			String addr1 = ticketBean.getAddr1();
			String addr2 = ticketBean.getAddr2();
			String addr3 = ticketBean.getAddr3();
			String user_id = ticketBean.getUserId();
			int price = ticketBean.getPrice();
			
			adminService.updateMailState(seq);
			
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("name", user_name);
			m.put("email", user_email);
			m.put("phone", phone);
			m.put("oneti", oneticket);
			m.put("twiti", twiticket);
			m.put("hiragana", hiragana);
			m.put("post", post);
			m.put("addr1", addr1);
			m.put("addr2", addr2);
			m.put("addr3", addr3);
			m.put("user_id", user_id);
			String fileName = "/order.txt";
			MailUtil.sendMail(user_email, fileName, m);
			jsonObject.put("result", "OK");
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put("errorMsg", e.getMessage());
		}
		return jsonObject;
	}
}